#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

const std::string Default_Dict_Path = "./dictionary.txt";
const std::string sep = ": ";

class Dict{
public:
	Dict(const std::string &dict_path = Default_Dict_Path): _dict_path(dict_path){}

	bool LoadDict(){
		std::ifstream in(_dict_path);
		if(!in.is_open()){
			LOG(LogLevel::DEBUG)<<"打开字典错误";
			return false;
		}

		// 逐行解析文件内容
		std::string line;
		while(std::getline(in, line)){
			int pos = line.find(sep);
			if(pos == std::string::npos)
				continue;

			std::string Eng = line.substr(0, pos);
			std::string Chi = line.substr(pos + sep.size());

			if(Eng.empty() || Chi.empty()){
				// LOG(LogLevel::WARNING)<<"解析行失败";
				continue;
			}

			_dict.insert(std::make_pair(Eng, Chi));
		}

		in.close();
		return true;
	}

	std::string Translate(const std::string& word, const InetAddr& addr){
		auto iter = _dict.find(word);
		if(iter == _dict.end()){
			LOG(LogLevel::DEBUG)<<"["<< addr.Ip() << ":" << addr.Port() << "] " <<"未找到翻译信息";
			return "None";
		}

		LOG(LogLevel::DEBUG)<<"["<< addr.Ip() << ":" << addr.Port() << "] " <<iter->second;
		return iter->second;
	}
	~Dict(){}

private:
	const std::string _dict_path;
	std::unordered_map<std::string, std::string> _dict;

};